from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
from . import constants


def generate_eccess_token(openid):

    # 创建序列化器对象
    # s = Serializer('秘钥:越复杂越安全', '过期时间')
    serializer = Serializer(settings.SECRET_KEY,
                            expires_in=constants.ACCESS_TOKEN_EXPIRES)

    data = {'openid':openid}

    token = serializer.dumps(data)

    return token.decode()


def check_eccess_token(access_token_openid):
    # 反解析
    s = Serializer(settings.SECRET_KEY,expires_in=constants.ACCESS_TOKEN_EXPIRES)

    try:
        data = s.loads(access_token_openid)
    except BadData:
        return None
    else:
        return data.get('openid')

